package xyz.zhouzhaodong.crm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.zhouzhaodong.crm.dto.ArriveSchoolDto;
import xyz.zhouzhaodong.crm.entity.ArriveSchool;
import xyz.zhouzhaodong.crm.entity.Customer;
import xyz.zhouzhaodong.crm.entity.RegistrationFee;
import xyz.zhouzhaodong.crm.mapper.ArriveSchoolMapper;
import xyz.zhouzhaodong.crm.mapper.CustomerMapper;
import xyz.zhouzhaodong.crm.mapper.RegistrationFeeMapper;
import xyz.zhouzhaodong.crm.mapper.StaffMapper;
import xyz.zhouzhaodong.crm.service.IArriveSchoolService;
import xyz.zhouzhaodong.crm.util.RestMessage;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 到校 服务实现类
 * </p>
 *
 * @author zhouzhaodong
 * @since 2020-06-19
 */
@Service
public class ArriveSchoolServiceImpl extends ServiceImpl<ArriveSchoolMapper, ArriveSchool> implements IArriveSchoolService {

    @Resource
    ArriveSchoolMapper arriveSchoolMapper;

    @Resource
    CustomerMapper customerMapper;

    @Resource
    StaffMapper staffMapper;

    @Resource
    RegistrationFeeMapper registrationFeeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage addArriveSchool(ArriveSchoolDto arriveSchoolDto) {
        try {
            ArriveSchool arriveSchool = arriveSchoolDtoToArriveSchool(arriveSchoolDto);
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            arriveSchool.setId(id);
            arriveSchool.setCreateUser(arriveSchoolDto.getStaffId());
            arriveSchool.setCreateTime(new Date());
            if(arriveSchool.getCollegeExpenses() != null && !"".equals(arriveSchool.getCollegeExpenses())){
                insertRegistrationFee(arriveSchoolDto);
            }
            arriveSchoolMapper.insert(arriveSchool);
            return RestMessage.success(id);
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage deleteArriveSchool(ArriveSchoolDto arriveSchoolDto) {
        try {
            ArriveSchool arriveSchool = new ArriveSchool();
            arriveSchool.setId(arriveSchoolDto.getId());
            arriveSchool.setFlag(1);
            arriveSchool.setUpdateUser(arriveSchoolDto.getStaffId());
            arriveSchool.setUpdateTime(new Date());
            arriveSchoolMapper.updateById(arriveSchool);
            QueryWrapper<RegistrationFee> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("customer_id", arriveSchoolDto.getCustomerId());
            queryWrapper.eq("staff_id", arriveSchoolDto.getStaffId());
            RegistrationFee r = registrationFeeMapper.selectOne(queryWrapper);
            if(r != null && r.getId() != null){
                r.setFlag(1);
                r.setUpdateUser(arriveSchoolDto.getStaffId());
                r.setUpdateTime(new Date());
                registrationFeeMapper.updateById(r);
            }
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage updateArriveSchool(ArriveSchoolDto arriveSchoolDto) {
        try {
            ArriveSchool arriveSchool = arriveSchoolDtoToArriveSchool(arriveSchoolDto);
            arriveSchool.setUpdateUser(arriveSchoolDto.getStaffId());
            arriveSchool.setUpdateTime(new Date());
            if(arriveSchool.getCollegeExpenses() != null && !"".equals(arriveSchool.getCollegeExpenses())){
                insertRegistrationFee(arriveSchoolDto);
            }
            arriveSchoolMapper.updateById(arriveSchool);
            return RestMessage.success();
        } catch (Exception e) {
            return RestMessage.failed(e.getMessage());
        }
    }

    @Override
    public RestMessage selectArriveSchool(ArriveSchoolDto arriveSchoolDto) {
        QueryWrapper<ArriveSchool> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", arriveSchoolDto.getCustomerId());
        if(arriveSchoolDto.getId() != null && !"".equals(arriveSchoolDto.getId())){
            queryWrapper.eq("id", arriveSchoolDto.getId());
        }
        if(arriveSchoolDto.getFlag() != null){
            queryWrapper.eq("flag", arriveSchoolDto.getFlag());
        } else {
            queryWrapper.eq("flag", 0);
        }
        List<ArriveSchool> list = arriveSchoolMapper.selectList(queryWrapper);
        return RestMessage.success(list);
    }

    @Override
    public RestMessage selectArriveSchoolList(ArriveSchoolDto arriveSchoolDto) {
        Integer flag = arriveSchoolDto.getFlag();
        if (flag == null) {
            arriveSchoolDto.setFlag(0);
        }
        Page<ArriveSchoolDto> page = new Page<>(arriveSchoolDto.getPageNo(),
                arriveSchoolDto.getPageSize() == 0 ? 10 : arriveSchoolDto.getPageSize());
        IPage<ArriveSchoolDto> list = arriveSchoolMapper.selectArriveSchoolList(arriveSchoolDto, page);
        for (ArriveSchoolDto a : list.getRecords()) {
            Customer customer = customerMapper.selectById(a.getCustomerId());
            a.setCustomer(customer);
        }
        return RestMessage.success(list);
    }

    private ArriveSchool arriveSchoolDtoToArriveSchool(ArriveSchoolDto arriveSchoolDto){
        ArriveSchool arriveSchool = new ArriveSchool();
        arriveSchool.setId(arriveSchoolDto.getId());
        arriveSchool.setCustomerId(arriveSchoolDto.getCustomerId());
        arriveSchool.setArrivalTime(arriveSchoolDto.getArrivalTime());
        arriveSchool.setExpensesStatus(arriveSchoolDto.getExpensesStatus());
        arriveSchool.setSchoolStatus(arriveSchoolDto.getSchoolStatus());
        arriveSchool.setCollegeExpenses(arriveSchoolDto.getCollegeExpenses());
        arriveSchool.setRemark(arriveSchoolDto.getRemark());
        arriveSchool.setFlag(arriveSchoolDto.getFlag());
        return arriveSchool;
    }

    public void insertRegistrationFee(ArriveSchoolDto arriveSchoolDto){
        // 日期	编号	姓名	国家	学校	入学季	报名费	学校押金	顾问
        String customerId = arriveSchoolDto.getCustomerId();
        Customer customer = customerMapper.selectById(customerId);
        RegistrationFee registrationFee = new RegistrationFee();
        registrationFee.setCustomerId(customerId);
        registrationFee.setStaffId(arriveSchoolDto.getStaffId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        registrationFee.setOperationTime(sdf.format(new Date()));
        registrationFee.setNumber(customer.getNumber());
        registrationFee.setName(customer.getName());
        registrationFee.setCountry(customer.getCountry());
        registrationFee.setSchool(customer.getSchool());
        registrationFee.setSpecialty(customer.getSpecialty());
        registrationFee.setEntranceSeason(customer.getEntranceSeason());
        String str = arriveSchoolDto.getCollegeExpenses();
        List<Map<String, String>> list = JSON.parseObject(str, new TypeReference<List<Map<String, String>>>(){});
        if(list != null  && list.size() > 2){
            registrationFee.setRegistrationFee(list.get(0).get("money"));
            registrationFee.setDeposit(list.get(1).get("money"));
        }
        registrationFee.setManager(staffMapper.selectById(arriveSchoolDto.getStaffId()).getName());
        registrationFee.setCustomerType(customer.getConnectType());
        QueryWrapper<RegistrationFee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        queryWrapper.eq("staff_id", arriveSchoolDto.getStaffId());
        RegistrationFee r = registrationFeeMapper.selectOne(queryWrapper);
        if(r == null || r.getId() == null){
            registrationFee.setCreateUser(arriveSchoolDto.getStaffId());
            registrationFee.setCreateTime(new Date());
            registrationFeeMapper.insert(registrationFee);
        } else {
            registrationFee.setId(r.getId());
            registrationFee.setUpdateUser(arriveSchoolDto.getStaffId());
            registrationFee.setUpdateTime(new Date());
            registrationFeeMapper.updateById(registrationFee);
        }
    }
}